package utils;

import io.seata.rm.datasource.xa.DataSourceProxyXA;
import mapper.JianMapper;
import mapper.NongMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.util.ResourceBundle;

public class FactoryUtils {

    /**
     * 获取第一个sqlSessionFactory
     */
    public static SqlSessionFactory nongSqlSessionFactory() {
        ResourceBundle bundle = ResourceBundle.getBundle("nonghang");
        String driver = bundle.getString("jdbc.driverClassName");
        String url = bundle.getString("jdbc.url");
        String username = bundle.getString("jdbc.username");
        String password = bundle.getString("jdbc.password");
        PooledDataSource pooledDataSource = new PooledDataSource(driver, url, username, password);
        //使用Seata提供的XA代理数据源 使用XA 解决分布式事务
        DataSourceProxyXA dataSource = new DataSourceProxyXA(pooledDataSource);
        TransactionFactory transactionFactory = new JdbcTransactionFactory
                ();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(NongMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder
                ().build(configuration);
        return sqlSessionFactory;
    }

    public static SqlSessionFactory jianSqlSessionFactory() {
        ResourceBundle bundle = ResourceBundle.getBundle("jianhang");
        String driver = bundle.getString("jdbc.driverClassName");
        String url = bundle.getString("jdbc.url");
        String username = bundle.getString("jdbc.username");
        String password = bundle.getString("jdbc.password");
        PooledDataSource pooledDataSource = new PooledDataSource(driver, url, username, password);
        //使用Seata提供的XA代理数据源 使用XA 解决分布式事务
        DataSourceProxyXA dataSource = new DataSourceProxyXA(pooledDataSource);
        TransactionFactory transactionFactory = new JdbcTransactionFactory
                ();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(JianMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder
                ().build(configuration);
        return sqlSessionFactory;
    }
}
